/*
 * @Author: HaoyangDu@wits.com
 * @description:
 * @param:
 * @return:
 */
// src/hooks/useImagePicker.js
import { reactive } from "vue";
import * as http from "@/utils/http";
import { useAppStore } from "@/store";
const store = useAppStore();
export function useImagePicker() {
  const tempFiles = reactive([]);
  const imgList = reactive([]);
  const imgInfoList = reactive([]);

  // 选择图片的函数
  const chooseImg = async () => {
    wx.chooseMedia({
      count: 9,
      mediaType: "mix",
      sourceType: "album",
      sizeType: ["original", "compressed"],
      success: (res) => {
        const tempFilePaths = res.tempFiles.map((item) => item.tempFilePath);
        imgList.push(...tempFilePaths);
        Promise.all(tempFilePaths.map(getBase64Data)).then((base64Datas) => {
          base64Datas.forEach((base64Data, index) => {
            const tempFilePath = tempFilePaths[index];
            imgInfoList.push({
              fileName: tempFilePath,
              fileBase64: base64Data.data,
              fileType: tempFilePath.split(".").pop(),
            });
          });
        });
      },
      fail: (err) => {
        console.log(err);
      },
    });
  };

  // 将图片文件转为 base64 字符串的函数
  const getBase64Data = (filePath) => {
    return new Promise((resolve, reject) => {
      wx.getFileSystemManager().readFile({
        filePath,
        encoding: "base64",
        success(res) {
          resolve({ data: res.data });
        },
        fail(err) {
          reject(err);
        },
      });
    });
  };

  // 上传文件处理后的fileInfoList
  const uploadFiles = async () => {
    const resImgListPromises = imgInfoList.map(async (item) => {
      try {
        const uploadResult = await http.uploadFile({
          bizType: "B0302",
          fileBase64: item.fileBase64,
          fileName: item.fileName,
          orderId: store.orderId,
          fileType: item.fileType,
        });
        return {
          bizType: "B0402",
          fileId: uploadResult.data.data.fileId,
        };
      } catch (error) {
        console.error("Error uploading file:", error);
        return null;
      }
    });

    const fileInfoList = (await Promise.all(resImgListPromises)).filter(
      (result) => result !== null
    );
    return fileInfoList;
  };

  // 返回响应式状态和方法
  return {
    imgList,
    imgInfoList,
    chooseImg,
    uploadFiles,
  };
}
